1 module hip.util.algorithm;
2 public import std.algorithm.iteration : map;
3 import std.algorithm.mutation : copy;
4 import std.traits:ReturnType;
5 
6 ///An alias made of std.algorithm.mutation.copy for the intention to be clearer since the `from` is the first argument
7 alias copyInto = copy;
8 
9 ReturnType!(Range.front)[] array(Range)(Range range)
10 {
11     typeof(return) ret;
12     foreach(v; range)
13         ret~= v;
14     return ret;
15 }
16 
17 auto map(Range, From, To)(Range range, scope To delegate (From data) func)
18 {
19     struct Return
20     {
21         Range inputRange;
22         To delegate(From data) convert;
23         import std.traits :isArray;
24         static if(isArray!Range)
25         {
26             size_t counter = 0;
27             void popFront(){counter++;}
28             bool empty(){return counter == inputRange.length;}
29             To front(){return convert(inputRange[counter]);}
30         }
31         else
32         {
33             void popFront(){inputRange.popFront;}
34             bool empty(){return inputRange.empty;}
35             To front(){return convert(inputRange.front);}
36         }
37 
38         int opApply(scope int delegate(To) dg)
39         {
40             foreach(v; inputRange)
41             {
42                 int ret = dg(convert(v));
43                 if(ret) return ret;
44             }
45             return 0;
46         }
47         int opApply(scope int delegate(size_t, To) dg)
48         {
49             size_t i = 0;
50             foreach(v; inputRange)
51             {
52                 int ret = dg(i++, convert(v));
53                 if(ret) return ret;
54             }
55             return 0;
56         }
57     }
58     return Return(range, func);
59 }
60 
61 void put(Q, T)(Q range, T[] args ...) if(is(T == U*, U))
62 {
63     int i = 0;
64     foreach(v; range)
65     {
66         if(i >= args.length)
67             return;
68         *args[i] = v;
69         i++;
70     }
71 }
72 
73 void swap(T)(ref T a, ref T b)
74 {
75     T tempA = a;
76     a = b;
77     b = tempA;
78 }
79 
80 
81 int find(T)(in T[] array, scope bool function(T val) pred)
82 {
83     foreach(index, v; array)
84         if(pred(v))
85             return cast(int)index;
86     return -1;
87 }
88 
89 int findLast(T)(in T[] array, scope bool function(T val) pred)
90 {
91     foreach_reverse(index, v; array)
92         if(pred(v))
93             return cast(int)index;
94     return -1;
95 }